package com.itmck.mq.deadconfirm;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.util.Map;


@Component
@Slf4j
@RabbitListener(queues = "spring.direct.ttl.queue")
public class DeadConfirmReceive {

    @RabbitHandler
    public void onOrderMessage(@Payload String message, Channel channel, @Headers Map<String, Object> headers) throws Exception {
        log.info("收到消息:{}, 开始消费", message);
        // 代表了 RabbitMQ 向该 Channel 投递的这条消息的唯一标识 ID，是一个单调递增的正整数，delivery tag 的范围仅限于 Channel
        Long deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
        try {
            //-----------------------------
            //处理业务逻辑
            //-----------------------------

            channel.basicAck(deliveryTag, false);
            log.info("处理业务逻辑成功并签收,deliveryTag:{}", deliveryTag);
        } catch (Exception e) {
            log.error("处理业务逻辑失败", e);
            //手工nack, requeue 第三个参数:再次入队列,如果配合死信队列,这里设置为false.直接进入死信队列
            channel.basicNack(deliveryTag, false, false);
            log.error("处理业务逻辑失败重新入队列:{}", deliveryTag);
        }
    }
}